<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter';
import { ref, onMounted } from 'vue';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { Button, InputSearch, message, Popconfirm, Select, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter';
import { getProjectMemberListApi, deleteProjectMemberApi, getProjectMemberDetailApi } from '#/api/project/member';
import MemberDrawer from './member-drawer.vue';
import { getOptionsApi, type Option } from '#/api/core/optiontool';
import { $t } from '#/locales';

const [Drawer, drawerApi] = useVbenDrawer({
  connectedComponent: MemberDrawer,
});

async function openDrawer(row?: any) {
  if (row?.id) {
    // 编辑模式：先调用后端接口获取详细数据
    try {
      const detailData = await getProjectMemberDetailApi(row.id);
      drawerApi.setData(detailData);
    } catch (error) {
      console.error($t('member.loadDetailFailed'), error);
      message.error($t('member.loadDetailFailed'));
      return;
    }
  } else {
    // 新增模式：传递空对象
    drawerApi.setData({});
  }
  drawerApi.open();
}

interface MemberType {
  id: string;
  name: string;
  sex: string;
  role: string;
  email: string;
}

// 添加角色选项的响应式引用
const roleOptions = ref<Option[]>([]);

// 添加加载角色选项的函数
async function loadRoleOptions() {
  try {
    const data = await getOptionsApi({
      pathOrBeanName: 'com.matrix.app.common.enums.Role'
    });
    roleOptions.value = data;
  } catch (error) {
    console.error($t('member.loadRoleOptionsFailed'), error);
  }
}

// 添加性别选项的响应式引用
const sexOptions = ref<Option[]>([]);

// 添加加载性别选项的函数
async function loadSexOptions() {
  try {
    const data = await getOptionsApi({
      pathOrBeanName: 'com.matrix.app.common.enums.Sex'
    });
    sexOptions.value = data;
  } catch (error) {
    console.error($t('member.loadSexOptionsFailed'), error);
  }
}

const searchText = ref('');
const selectedRows = ref<MemberType[]>([]);
const selectedRole = ref('');
const selectedSex = ref('');

const gridOptions: VxeGridProps<MemberType> = {
  columns: [
    { type: 'checkbox', width: 40 },
    { title: $t('common.seq'), type: 'seq', width: 50 },
    { field: 'name', title: $t('member.name') },
    { field: 'role', title: $t('member.role') },
    { field: 'sex', title: $t('member.sex') },
    { field: 'phone', title: $t('member.phone') },
    { field: 'email', title: $t('member.email') },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: $t('common.action.name'),
      width: 140,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await getProjectMemberListApi({
          page: page.currentPage,
          pageSize: page.pageSize,
          searchKey: searchText.value,
          role: selectedRole.value,
          sex: selectedSex.value,
        });
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

async function handleDelete(row: any) {
  try {
    await deleteProjectMemberApi(row.id);
    await gridApi.reload();
    message.success($t('common.action.deleteSuccess'));
  } catch {
    message.error($t('common.submit.failed'));
  }
}

function handleSave() {
  gridApi.reload();
}

function handleSearch() {
  gridApi.reload();
}

const gridEvents = {
  checkboxChange({ records }: { records: any[] }) {
    selectedRows.value = records;
  },
  checkboxAll({ records }: { records: any[] }) {
    selectedRows.value = records;
  },
};

async function handleDeleteSelected() {
  if (selectedRows.value.length === 0) return;

  Modal.confirm({
    title: $t('role.delete.title'),
    content: $t('role.delete.batchConfirm', { count: selectedRows.value.length }),
    okText: $t('common.yes'),
    cancelText: $t('common.no'),
    async onOk() {
      try {
        await Promise.all(selectedRows.value.map(row => deleteProjectMemberApi(row.id)));
        selectedRows.value = [];
        await gridApi.reload();
        message.success($t('common.action.deleteSuccess'));
      } catch {
        message.error($t('common.submit.failed'));
      }
    }
  });
}

onMounted(() => {
  loadRoleOptions();
  loadSexOptions();
});
</script>

<template>
  <Page auto-content-height>
    <Drawer :on-save="handleSave" :role-options="roleOptions" :sex-options="sexOptions" />
    <Grid :grid-events="gridEvents">
      <template #toolbar-actions>
        <Button type="primary" @click="() => openDrawer()">
          {{ $t('common.action.add') }}
        </Button>
        <Button
          v-if="selectedRows.length > 0"
          class="ml-2"
          danger
          type="primary"
          @click="handleDeleteSelected"
        >
          {{ $t('common.action.delete') }}
        </Button>
      </template>
      <template #toolbar-tools>
        <div style="display: flex; align-items: center; gap: 12px;">
          <Select
            v-model:value="selectedRole"
            :options="roleOptions"
            :placeholder="$t('member.role')"
            style="width: 120px"
            allow-clear
            @change="handleSearch"
          />
          <Select
            v-model:value="selectedSex"
            :options="sexOptions"
            :placeholder="$t('member.sex')"
            style="width: 120px"
            allow-clear
            @change="handleSearch"
          />
          <InputSearch
            v-model:value="searchText"
            :placeholder="$t('common.search')"
            @search="handleSearch"
            style="width: 200px"
            allow-clear
          />
        </div>
      </template>
      <template #action="{ row }">
        <Button type="link" @click="() => openDrawer(row)">{{ $t('common.action.edit') }}</Button>
        <Popconfirm
          :title="$t('common.delete.confirm')"
          :ok-text="$t('common.yes')"
          :cancel-text="$t('common.no')"
          @confirm="async () => await handleDelete(row)"
        >
          <Button type="link" danger>{{ $t('common.action.delete') }}</Button>
        </Popconfirm>
      </template>
    </Grid>
  </Page>
</template>

<style scoped>
</style>
